
import cv2
import time

 
def get_img_from_camera_net(folder_path,url):
    cap = cv2.VideoCapture(url)#定义摄像头对象
    # 按帧读取视频，其中ret是bool值（如果读取帧是正确的则返回True，如果文件读到结尾，返回值为False）
    # frame是每一帧的图像，是个三维矩阵，frame颜色空间是ＢＧＲ
    ret, frame = cap.read()
    print('摄像头数据以获取')
    if ret is True:
        i = 0
        timeF = 250 #每隔25帧提取一次图片，本摄像头每秒内会有25帧，所以要实现每秒截一张图片，则每25帧保存一帧图片
        while True:
            
            i = i + 1
            if(i % timeF == 0):
                cv2.imwrite(folder_path + 'temp_temp' + ".jpg", frame)  # 存储为图像，图像以当前时间命名
                print('截图已保存')
                
            ret, frame = cap.read()
            if ret is False:
                print("断开连接，自主重连")
                cap = cv2.VideoCapture(url)
                ret, frame = cap.read()                
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        cap.release()
        cv2.destroyAllWindows()
        
    else:
        cap = cv2.VideoCapture(url)
        ret, frame = cap.read()
        print("断开连接，自主重连")


def get_interval_time(folder_path , url):
    cap = cv2.VideoCapture(url)


    c = 1
    timeRate = 10

    while(True):
        ret, frame = cap.read()
        


        if ret:
            
            
            cv2.imwrite(folder_path + 'temp_temp' + ".jpg", frame) 
            print('image saved')
            
            
        else:
            cap = cv2.VideoCapture(url)
            ret, frame = cap.read()

        time.sleep(10)
    cap.release()

    
 
# 测试
if __name__ == '__main__':
    folder_path = "pics/" #存储图片的本地路径
    url = 'rtsp://admin:ycga20620@172.26.61.128' #网络摄像头的用户名、密码、IP
    get_img_from_camera_net(folder_path , url)
